#!/bin/sh
if [ -z "$S" ] ; then
	echo 'S not set, did you source config?'
	exit 1
fi

pkg=$1
if [ -z "$pkg" ] ; then
	echo 'this script pretty-prints the specified package.'
	echo 'need package name as argv!'
	exit 1
fi

fl=$S/pkg/$pkg
if [ ! -e "$fl" ] ; then
	echo "package $fl does not exist!"
	exit 1
fi

printbody() {
awk '
	function getline2(i) {
		i = getline;
		if(i != 1) exit;
	}
	{
		while($1 != "\['$1'\]") { getline2(); }
		getline2();
		while($0 ~ /^$/) { getline2(); }
		if($1 ~ /\[[a-z\.]+\]/) exit;
		while($1 !~ /\[[a-z\.]+\]/) { print $0; getline2(); }
	}
' $fl
}

printsec() {
# skip [sections] that have empty bodies.
if [ `printbody $1 |sort -ub |sed '/./,$!d' |wc -l` -gt 0 ] ; then
	if [ ! -z $2 ]; then                                                 
		echo "[$1]"	
		printbody $1 |sort -ub |sed '/./,$!d'
		echo
	else
		echo "[$1]"
		printbody $1 | sed -e :a -e '/^\n*$/{$d;N;};/\n$/ba'
		echo
	fi
fi
}

printsec mirrors
printsec main sort
printsec deps sort
printsec deps.host sort
printsec deps.run sort
printsec build
exit 0
